package com.example.musicplayer

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.musicplayer.dao.MusicDAOImpl
import com.example.musicplayer.model.Song
import com.example.musicplayer.util.CategoryDatabaseHelper
import com.example.musicplayer.model.SongCategory

class AddSongActivity : AppCompatActivity() {

    private lateinit var editTextTitle: EditText
    private lateinit var editTextArtist: EditText
    private lateinit var spinnerCategory: Spinner
    private lateinit var buttonSelectImage: Button
    private lateinit var buttonSelectAudio: Button
    private lateinit var buttonAddSong: Button
    private lateinit var recyclerViewSongs: RecyclerView

    private var imageUri: Uri? = null
    private var audioUri: Uri? = null
    private lateinit var musicDAO: MusicDAOImpl
    private lateinit var categoryDatabaseHelper: CategoryDatabaseHelper
    private var selectedCategoryId: Int = -1

    private lateinit var songAdapter: SongAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_add_song)

        editTextTitle = findViewById(R.id.editTextTitle)
        editTextArtist = findViewById(R.id.editTextArtist)
        spinnerCategory = findViewById(R.id.spinnerCategory)
        buttonSelectImage = findViewById(R.id.buttonSelectImage)
        buttonSelectAudio = findViewById(R.id.buttonSelectAudio)
        buttonAddSong = findViewById(R.id.buttonAddSong)
        recyclerViewSongs = findViewById(R.id.recyclerViewSongs)

        musicDAO = MusicDAOImpl(this)
        categoryDatabaseHelper = CategoryDatabaseHelper(this)

        setupSpinner()
        setupRecyclerView()

        buttonSelectImage.setOnClickListener { openImagePicker() }
        buttonSelectAudio.setOnClickListener { openAudioPicker() }
        buttonAddSong.setOnClickListener { addSongToDatabase() }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_PERMISSION_READ_EXTERNAL_STORAGE)
        }

        loadSongs()
    }

    private fun setupSpinner() {
        val categories = loadCategories()
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, categories.map { it.name })
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerCategory.adapter = adapter

        spinnerCategory.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                selectedCategoryId = categories[position].id
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
                // Do nothing
            }
        }
    }

    private fun loadCategories(): List<SongCategory> {
        val categories = mutableListOf<SongCategory>()
        val db = categoryDatabaseHelper.readableDatabase
        val cursor = db.query(
            CategoryDatabaseHelper.TABLE_SONG_CATEGORY,
            arrayOf(CategoryDatabaseHelper.COLUMN_CATEGORY_ID, CategoryDatabaseHelper.COLUMN_CATEGORY_NAME),
            null, null, null, null, null
        )

        while (cursor.moveToNext()) {
            val categoryId = cursor.getInt(cursor.getColumnIndexOrThrow(CategoryDatabaseHelper.COLUMN_CATEGORY_ID))
            val categoryName = cursor.getString(cursor.getColumnIndexOrThrow(CategoryDatabaseHelper.COLUMN_CATEGORY_NAME))
            categories.add(SongCategory(categoryId, categoryName))
        }

        cursor.close()
        return categories
    }

    private fun setupRecyclerView() {
        songAdapter = SongAdapter(emptyList(), object : SongAdapter.OnItemClickListener {
            override fun onItemClick(song: Song) {
                Toast.makeText(this@AddSongActivity, "Clicked: ${song.title}", Toast.LENGTH_SHORT).show()
            }
        })
        recyclerViewSongs.layoutManager = LinearLayoutManager(this)
        recyclerViewSongs.adapter = songAdapter
    }

    private fun loadSongs() {
        val allSongs = musicDAO.getAllSongs() // 确保这个方法返回所有歌曲
        if (allSongs.isEmpty()) {
            Log.w("AddSongActivity", "No songs found in the database")
        } else {
            Log.d("AddSongActivity", "Loaded ${allSongs.size} songs from the database")
        }
        songAdapter.updateData(allSongs)
    }

    private fun openImagePicker() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, REQUEST_IMAGE_PICK)
    }

    private fun openAudioPicker() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, REQUEST_AUDIO_PICK)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_IMAGE_PICK -> {
                    imageUri = data?.data
                }
                REQUEST_AUDIO_PICK -> {
                    audioUri = data?.data
                }
            }
        }
    }

    private fun addSongToDatabase() {
        val title = editTextTitle.text.toString()
        val artist = editTextArtist.text.toString()
        val audioPath = audioUri?.toString() ?: ""
        val imageBytes = imageUri?.let { uri ->
            contentResolver.openInputStream(uri)?.use { inputStream ->
                inputStream.readBytes()
            }
        } ?: byteArrayOf()

        if (selectedCategoryId != -1) {
            val song = Song(title = title, artist = artist, image = imageBytes, audioPath = audioPath, categoryId = selectedCategoryId)
            musicDAO.addSong(song)
            Log.d("AddSongActivity", "Song added to database: $song")
            Toast.makeText(this, "Song added successfully", Toast.LENGTH_SHORT).show()
            loadSongs()
        } else {
            Log.e("AddSongActivity", "No category selected")
            Toast.makeText(this, "Please select a category", Toast.LENGTH_SHORT).show()
        }
    }

    companion object {
        private const val REQUEST_PERMISSION_READ_EXTERNAL_STORAGE = 1
        private const val REQUEST_IMAGE_PICK = 2
        private const val REQUEST_AUDIO_PICK = 3
    }
}